<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
App::import('Model', 'tattlrAccount');

class Account extends AppModel {

    var $primaryKey = 'accID';
    var $validate = array('name' => array('must enter a name' => array('rule' => 'notEmpty', 'message' => 'Please enter account name'))
        , 'Minimum Duration' => array('must enter min duration' => array('rule' => 'notEmpty', 'message' => 'Please enter minimum duration'),
            'must be a number' => array('rule' => 'numeric', 'message' => 'Please enter a valid number'))
    );

    function isUnique($field, $value) {
        $fields[$this->name . '.' . $field] = $value;


        $this->recursive = -1;
        if ($this->hasAny($fields)) {
            $this->invalidate('unique_' . $field);
            return false;
        }
        else
            return true;
    }

    function getAccountNamesAdmin() {
        return $this->query('select name from accounts Account join tattlr_accounts TattlrAccount on Account.accID=TattlrAccount.accID where TattlrAccount.isDeleted=0');
    }

    function getAccountNames($userID) {
        return $this->query("select accounts.name from accounts_has_users, tattlr_accounts, accounts where accounts.accID = tattlr_accounts.accID AND tattlr_accounts.accID = accounts_has_users.accID AND tattlr_accounts.isDeleted = 0 AND accounts_has_users.userID = " . $userID);
    }

    function getAccountIdByName($name) {
        return $this->find('all', array('conditions' => array('name' => $name), 'fields' => array('accID')));
    }

	/**
	* Description of (getAccountNameByAccID)
	*
	* This function takes an account ID and returns its twitter name
	*
	* @param int $accID
	*
	* @author karim kamel
	*/
	function getAccountNameByAccID($accID) {
        return $this->find('all', array('conditions' => array('accID' => $accID), 'fields' => array('name')));
    }
    /**
     * Description of "assignPos" 
     * 
     * This function takes the modified arrays of users and insert each user in the database table 
     * account_has_users each one with his specified permission...
	 *
	 * @param array $mod
     * @param array $ed
     * @param array $jed
	 *
	 * @author karim kamel
     */
    function assignPos($mod, $ed, $jed, $accID) {
        $this->query("delete from accounts_has_users where accounts_has_users.accID = " . $accID . " ");
        if ($mod[0] == "empty" && $ed[0] == "empty" && $jed[0] == "empty") {
            
        } else {
            for ($i = 0; $i < count($mod); $i++) {
                $username = $mod[$i];
                $user = new User();
                $modID = $user->getUserID($username);
                $userID = $modID[0]['User']['userID'];
                $this->query("insert into accounts_has_users(accID,userID,permissionLevel) values(" . $accID . "," . $userID . ",3)");
            }
            for ($j = 0; $j < count($ed); $j++) {
                $username = $ed[$j];
                $user = new User();
                $edID = $user->getUserID($username);
                $userID = $edID[0]['User']['userID'];
                $this->query("insert into accounts_has_users(accID,userID,permissionLevel) values(" . $accID . "," . $userID . ",2)");
            }
            for ($k = 0; $k < count($jed); $k++) {
                $username = $jed[$k];
                $user = new User();
                $jedID = $user->getUserID($username);
                $userID = $jedID[0]['User']['userID'];
                $this->query("insert into accounts_has_users(accID,userID,permissionLevel) values(" . $accID . "," . $userID . ",1)");
            }
        }
    }

    /*
     * Checks if account exists in the db,then checks if user has permission for this account on twitter or not(access not revoked).
     * @param  $accountID
     * @return bool
     * @author "Omar Ruedy"
     */

    function accountIsAuthorized($accountID) {
        $tempAccount = new tattlrAccount();
        $account = $tempAccount->getTattlrAccountKeys($accountID);
        if (!empty($account)) {
            $connection = new TwitterOAuth('S9Ww3avoaAONgzqU27DKMQ', 'gPcguIyyKbZlCrlBsKDIKqNCDqu558tfkRdsipoGw', $account['0']['tattlrAccount']['oauthToken'], $account['0']['tattlrAccount']['oauth_token_secret']);
            $content = $connection->get('account/verify_credentials');
            if ($connection->http_code == 200) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /*
     * Requests a connection object on which twitter api calls can be called upon.
     * @param  $accountID
     * @return TwitterOAuth $connection
     * @author "Omar Ruedy"
     */

    function connectionRequest($accountID) {
        if ($this->accountIsAuthorized($accountID)) {
            $tempAccount = new tattlrAccount();
            $account = $tempAccount->getTattlrAccountKeys($accountID);
            $connection = new TwitterOAuth('S9Ww3avoaAONgzqU27DKMQ', 'gPcguIyyKbZlCrlBsKDIKqNCDqu558tfkRdsipoGw', $account['0']['tattlrAccount']['oauthToken'], $account['0']['tattlrAccount']['oauth_token_secret']);
            $content = $connection->get('account/verify_credentials');
            return $connection;
        }
        else
            return FALSE;
    }

    function getMentionAuthor($accID) {

        return $this->find('all', array('conditions' => array('accID' => $accID), 'fields' => array('twitterName', 'image')));
    }

    /**
     * Checks if a given account exists in the System.
     * @param varchar accID; the Account ID to be checked.
     * @return Returns the result of the query.
     * @author Kareem Yousry
     */
    function checkAccount($accID) {
        return $this->find('all', array('conditions' => array('accId' => $accID)));
    }

    /**
     * Given an accountID, this function will returns all
     * moderators in this account
     */
    function getAllModerators($accID) {
        return $this->query("SELECT users.userID
            FROM accounts_has_users, users
            WHERE users.userID = accounts_has_users.userID
            AND accounts_has_users.accID =" . $accID . " AND (accounts_has_users.permissionLevel = 3)");
    }

    /*
     * Description of "getAccount"
     * @param  "postid" 
     *
     * This function gets the account information who did a certain post

     * @author "Sherif Ismail"
     */

    public function getAccount($postid) {
        $options['joins'] = array(
            array('table' => 'posts',
                'alias' => 'Post',
                'type' => 'inner',
                'conditions' => array(
                    'Account.accID = Post.accID ',
                )
            )
        );
        $options['conditions'] = array('Post.PostID' => $postid);

        $tem = $this->find('all', $options);
        return $tem;
    }

    /**
     * Gets the followers of the authorized account
     *
     * @access: public
     * @param: $accountID, the id of the authorized account
     * @return: An array of ids of the followers
     *
     * @author "Hussein Abo El Seoud"
     */
    public function getFollowers($accountID) {
        $result = $this->find('first', array('conditions' => array("Account.accID" => $accountID)));
        $username = $result['Account']['twitterName'];
        $array = (array) $this->connectionRequest($accountID)->get('followers/ids', array('screen_name' => $username));
        return $array['ids'];
    }

    public function addAccount($accountID, $twittername, $image, $name) {
        /* debug($accountID);
          debug($twittername);
          debug($image);
          debug($name);
          $this->save(array('Account' =>
          array(
          'accID' => $accountID,
          'twitterName' => $twittername,
          'image' => $image,
          'name' => $name
          )
          )
          ); */
        $this->query("insert into accounts (accID, twitterName, image, name) values('" . $accountID . "','" . $twittername . "','" . $image . "','" . $name . "')");
        $this->query("insert into twitter_accounts values ('" . $accountID . "')");
    }
    /**
     *@author Moataz Ezzo
     *This function retriive users in an account from the database
     */
    function getUsers($accID, $userID) {

         return $this->query("SELECT users.userID,users.username
            FROM accounts_has_users, users
            WHERE users.deleted = 0 AND users.userID = accounts_has_users.userID
            AND accounts_has_users.accID =" . $accID . " AND (users.userID != '$userID')");
    }


}

?>